package cn.geminis.workflow.service.service.engine.expression;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.NotImplementedException;
import org.flowable.common.engine.api.variable.VariableContainer;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

/**
 * @author puddi
 */
@RequiredArgsConstructor
public class JsonVariableContainer implements VariableContainer {

    private final Map<String, Object> object;

    private Iterator<String> getPath(String key) {
        return Arrays.stream(key.split("\\.")).iterator();
    }

    @Override
    public boolean hasVariable(String key) {
        var path = this.getPath(key);
        var currentObject = this.object;
        while (path.hasNext()) {
            var currentKey = path.next();
            if (path.hasNext()) {
                if (currentObject.containsKey(currentKey)) {
                    currentObject = (Map<String, Object>) currentObject.get(currentKey);
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public Object getVariable(String key) {
        var path = this.getPath(key);
        var currentObject = this.object;
        while (path.hasNext()) {
            var currentKey = path.next();
            if (path.hasNext()) {
                if (currentObject.containsKey(currentKey)) {
                    currentObject = (Map<String, Object>) currentObject.get(currentKey);
                } else {
                    return null;
                }
            } else {
                return currentObject.getOrDefault(currentKey, null);
            }
        }
        return null;
    }

    @Override
    public void setVariable(String key, Object value) {
        throw new NotImplementedException();
    }

    @Override
    public void setTransientVariable(String key, Object value) {
        throw new NotImplementedException();
    }

    @Override
    public String getTenantId() {
        throw new NotImplementedException();
    }
}
